<?php

namespace app\controller;

use plugin\admin\app\service\v1\OptionService;
use plugin\admin\app\service\v1\UserRechargeService;
use support\Log;
use support\Request;
use support\Response;
use support\exception\BusinessException;
use Yansongda\Pay\Pay;

class PaymentController
{

    /**
     * 支付宝异步通知
     * @param Request $request
     */
    public function alipayNotify(Request $request)
    {
        $data = $request->all();
        $log = Log::channel('alipay_notify');
        $log->info('【支付宝异步通知】', $data);

        $config = OptionService::getConfig('pay');
        $aliPay = new \plugin\admin\app\common\alipay\Notify();
        $aliPay->setAlipayPublicKey($config['alipay_public_cert_path']);
        try {
            $res = $aliPay->rsaCheck($request->all());
            if ($res) {
                $log->info('【支付宝异步通知】 签名验证成功', []);
                if ($data['trade_status'] == "TRADE_SUCCESS") {
                    $payamount = $data['total_amount'];
                    $out_trade_no = $data['out_trade_no'];
                    $trade_no = $data['trade_no'];
                    $result = UserRechargeService::order_settle($payamount, $out_trade_no, $trade_no);
                    $log->info('【支付宝异步通知】 订单处理', ['out_trade_no' => $out_trade_no, 'error' => $result['msg']]);

                    // 异步响应
                    return new Response(200, [], 'success');
                }
            }
        } catch (BusinessException $e) {
            $log->info('【支付宝异步通知】 业务异常', [
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
        } catch (\Exception $e) {
            // 捕获所有其他异常，避免500错误导致支付宝重试
            $log->error('【支付宝异步通知】 系统异常', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
        }
    }

    /**
     * 微信异步通知
     * @param Request $request
     **/
    public function wechatNotify(Request $request)
    {
        // 在Webman中获取原始请求体的正确方式
        $data = request()->rawBody();
        $log = Log::channel('wechat_notify');
        $log->info('【微信异步通知】 ' . json_encode($data, JSON_UNESCAPED_UNICODE), []);

        $config = OptionService::getConfig('pay');
        $wxPay = new \plugin\admin\app\common\wechatpay\Notify($config['wechat_mch_id'], $config['wechat_app_id'], $config['wechat_mch_secret_key_v2']);
        try {
            $res = $wxPay->notify();
            if ($res) {
                $log->info('【微信异步通知】 签名验证成功', $res);
                if ($res['return_code'] == 'SUCCESS') {
                    $payamount = $res['total_fee'] / 100;
                    $out_trade_no = $res['out_trade_no'];
                    $trade_no = $res['transaction_id'];
                    $result = UserRechargeService::order_settle($payamount, $out_trade_no, $trade_no);
                    $log->info('【微信异步通知】 订单处理', ['out_trade_no' => $out_trade_no, 'error' => $result['msg']]);

                    // 异步响应
                    return new Response(200, [], 'success');
                }
            }
        } catch (BusinessException $e) {
            $log->info('【微信异步通知】 业务异常', [
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
        } catch (\Exception $e) {
            // 捕获所有其他异常，避免500错误导致支付宝重试
            $log->error('【微信异步通知】 系统异常', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
        }
    }

    /**
     * 微信异步通知
     * @param Request $request
     **/
    public function wechatNotify1(Request $request)
    {
        $log = Log::channel('wechat_notify');
        $log->info('【微信异步通知】', $request->all());

        // 1. 初始化配置
        $config = config('payment');
        Pay::config($config);

        // 2. 微信回调处理
        $result = Pay::wechat()->callback($request->post());
        $log->info('【微信异步通知解密】', json_decode($result, true));

        // 接受回调信息
        $thirdSn = $result['resource']['ciphertext']['transaction_id'];
        $outTradeNo = $result['resource']['ciphertext']['out_trade_no'];
        $totalAmount = bcdiv((string)$result['resource']['ciphertext']['amount']['total'], '100', 2);

        $payamount = $totalAmount;
        $out_trade_no = $outTradeNo;
        $trade_no = $thirdSn;
        UserRechargeService::order_settle($payamount, $out_trade_no, $trade_no);

        // 异步响应
        return new Response(200, [], 'success');
    }

    /**
     * 获取充值订单状态
     **/
    public function getQueryRecharge(Request $request)
    {
        $id = (integer)$request->input('id', 0);
        try {
            UserRechargeService::getQueryRecharge($id);
        } catch (BusinessException $e) {
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
        return json(['code' => 0, 'msg' => '支付成功']);
    }

}
